package com.OnTimeTeam.OnTime;


import java.util.List;
import java.util.Locale;

import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;

public class DefaultsAddAddressToLocationsAsyncTask extends AsyncTask<String, Void, Boolean> {

	private ProgressDialog progressDialog;
	private Context host;
	private String address;
	private String sort;
	private boolean result;
	
	public DefaultsAddAddressToLocationsAsyncTask(Context host, String address, String sort) {
		
		this.host = host;
		this.address = address;
		this.sort = sort;
	}
	
    protected Boolean doInBackground(String... params) {//In Background
    	
    	
    	int geoCoderResultType = 1; //OK
		
		Geocoder geocoder = new Geocoder(host, Locale.getDefault());
		List<Address> geoResults;
		try {
			geoResults = geocoder.getFromLocationName(address, 1);
		    if (geoResults.size() == 0)
		    	return false;
		    
		} catch (Exception e) {geoCoderResultType = 2;}
		
		if(geoCoderResultType == 2) {//Was Exception
			
			try{Thread.sleep(1500);}catch(Exception e){}
			
			boolean isValidAddress = RegularRoadsQuery.addressVerificationByGeoCoder(address);
			
			if(!isValidAddress) 
				return false;
		}
		
		return true;
    }      

    protected void onPreExecute() {//Before
    	super.onPreExecute();
    	
    	progressDialog = ProgressDialog.show(host, host.getResources().getString(R.string.searching), host.getResources().getString(R.string.pleaseWait));
    }
    
    protected void onPostExecute(Boolean result) {//After

    	progressDialog.dismiss();
    	
    	this.result = result;
    	
    	if(result) {
    		((Preferences)host).addAddress(address, sort);
    	}
    	else {
			((Preferences)host).showToast(host.getResources().getString(R.string.theAddress) + " " + address + " " + host.getResources().getString(R.string.isInvalid));
    	}

    }
    
    public boolean getResult() {
    	return result;
    }
	
    protected void onProgressUpdate(Void... values) {
    	
    	
    }
}

